package com.stx.crazy.action;

import java.util.Map;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.stx.crazy.entity.User;
import com.stx.crazy.service.UserService;
import com.stx.crazy.util.MD5_Test;

public class UserAction extends ActionSupport {
	private User user;
	private UserService service;
	private String nickName;
	private String passWord;

	public UserService getService() {
		return service;
	}

	public void setService(UserService service) {
		this.service = service;
	}

	// 注册用户模块
	public String addUser() throws Exception {
		service.addUser(user);
		return "success";
	}

	// 用户登录模块
	public String login() throws Exception {

		User currentUser = service.getUserByLoginNameAndPassword(
				user.getUs_loginName(), user.getUs_passWord());

		if (currentUser != null) {
			ActionContext context = ActionContext.getContext();
			Map<String, Object> session = context.getSession();
			session.put("currentUser", currentUser);
			return SUCCESS;
		} else {
			addActionError("用户名或密码错误!");
			return INPUT;
		}
	}

	// 更改用户信息模块
	public String update() throws Exception {
		User u = (User) ServletActionContext.getRequest().getSession()
				.getAttribute("user");

		if (u != null) {
			user.setUs_nickName(u.getUs_nickName());
			user.setUs_img(u.getUs_img());
		} else {
			addActionError("请重新登录");
			return "sessionerror";
		}

		if (!nickName.equals(u.getUs_nickName())) {

			addActionError("昵称已被占用");
			return "failture";
		} else {
			user.setUs_nickName(user.getUs_nickName());
			service.updateUser(user);
			addActionMessage("修改用户信息成功");
			return "success";
		}
	}

	public String updatePassWord() throws Exception {
		User u = (User) ServletActionContext.getRequest().getSession()
				.getAttribute("user");

		if (u != null) {

			user.setUs_id(u.getUs_id());
			user.setUs_img(u.getUs_img());
			user.setUs_loginName(u.getUs_loginName());
			user.setUs_nickName(u.getUs_nickName());

		} else {
			addActionError("请重新登录");
			return "sessionerror";
		}

		passWord = MD5_Test.MD5(passWord);
		if (!u.getUs_passWord().equals(passWord)) {
			addActionError("密码输入错误");
			return "failure";
		} else {
			user.setUs_passWord(MD5_Test.MD5(user.getUs_passWord()));
			service.updateUser(user);
			addActionError("密码修改成功");
			user = service.getUserByLoginNameAndPassword(
					user.getUs_loginName(), user.getUs_passWord());
			ServletActionContext.getRequest().getSession()
					.setAttribute("user", user);
			return "success";
		}
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

}
